package com.cjd.common.utils

import android.app.Activity
import android.content.Context
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.os.Build
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import java.util.*

/**
 * @Author chenjidong
 * @email 374122600@qq.com
 * created 2019/10/17
 * description 运行时权限申请处理 util
 */
object PermissionUtil {

    private const val REQUEST_PERMISSION_CODE = 8888
    private val unauthorized = mutableListOf<String>()

    private var callback: ((deniedPermissionList: List<String>) -> Unit)? = null
    private var isDenied = false

    private var sharedPreferences: SharedPreferences? = null

    @JvmStatic
    fun getPreferences(context: Context): SharedPreferences {
        if (sharedPreferences == null) {
            sharedPreferences = context.getSharedPreferences("runtime_permission", Activity.MODE_PRIVATE)
        }
        return sharedPreferences!!
    }

    @JvmStatic
    fun getPreferenceEdit(context: Context): SharedPreferences.Editor {
        return getPreferences(context).edit()
    }

    @JvmStatic
    fun hasDeniedPermission(context: Context, per: String): Boolean {
        return getPreferences(context).getBoolean(per, false)
    }

    @JvmStatic
    fun saveDeniedPermission(context: Context, per: String, value: Boolean = true) {
        getPreferenceEdit(context).putBoolean(per, value).apply()
    }

    @JvmStatic
    fun requestPermissions(
        context: Activity,
        block: ((deniedPermissionList: List<String>) -> Unit),
        vararg permissions: String,
        showDialog: Boolean = false,
        showDenied: Boolean = false,
        showDialogMsg: String = "App需要授权指定的权限才能正常使用，是否授权？"
    ) {
        this.isDenied = showDenied
        callback = block
        unauthorized.clear()
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            callback?.invoke(Collections.emptyList())
            return
        }
        var isShowDialog = showDialog
        for (per in permissions) {

            if (ContextCompat.checkSelfPermission(context, per) == PackageManager.PERMISSION_DENIED && hasDeniedPermission(context, per)) {
                //华为 等少数品牌 在首次授权就直接可以 选择不再提示选项
                unauthorized.add(per)
                this.isDenied = true
            } else if (ContextCompat.checkSelfPermission(context, per) == PackageManager.PERMISSION_DENIED && ActivityCompat.shouldShowRequestPermissionRationale(context, per)) {
                //用户拒绝过一次
                isShowDialog = true
                unauthorized.add(per)
            } else if (ContextCompat.checkSelfPermission(context, per) != PackageManager.PERMISSION_GRANTED) {
                unauthorized.add(per)
            }
        }
        if (unauthorized.isEmpty()) {
            callback?.invoke(Collections.emptyList())
        } else {
            if (this.isDenied) {
                val list = mutableListOf<String>()
                list.addAll(unauthorized)
                callback?.invoke(list)
            } else if (isShowDialog) {
                AlertDialog.Builder(context)
                    .setMessage(showDialogMsg)
                    .setPositiveButton("好的") { dialog, _ ->
                        dialog.dismiss()
                        ActivityCompat.requestPermissions(
                            context,
                            unauthorized.toTypedArray(),
                            REQUEST_PERMISSION_CODE
                        )
                    }
                    .setNegativeButton("取消") { dialog, _ ->
                        dialog.dismiss()
                        val list = mutableListOf<String>()
                        list.addAll(unauthorized)
                        callback?.invoke(list)
                    }.create().show()
            } else {
                ActivityCompat.requestPermissions(
                    context,
                    unauthorized.toTypedArray(),
                    REQUEST_PERMISSION_CODE
                )
            }
        }
    }

    @JvmStatic
    fun onRequestPermissionsResult(
        activity: Activity,
        requestCode: Int, permissions: Array<out String>, grantResults: IntArray
    ) {
        if (requestCode != REQUEST_PERMISSION_CODE)
            return

        if (grantResults.isEmpty())
            return

        val deniedPermissionList = mutableListOf<String>()

        for (i in grantResults.indices) {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                deniedPermissionList.add(permissions[i])
                //不在提示
                if (!ActivityCompat.shouldShowRequestPermissionRationale(activity, permissions[i])) {
                    this.isDenied = true
                    saveDeniedPermission(activity, permissions[i], false)
                }
            }
        }

        if (deniedPermissionList.isEmpty()) {
            callback?.invoke(deniedPermissionList)
            return
        }

        if (isDenied)
            Toast.makeText(activity, "当前应用缺少对应权限,请到[设置]-[应用权限] 打开", Toast.LENGTH_LONG)
                .show()
        callback?.invoke(deniedPermissionList)
    }
}